迷宫问题
Description
定义一个二维数组: int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。 Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample Input 0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0 Sample Output (0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4) Source |
bfs+回溯路径,用一个vist记录就行,具体看代码。
#include <iostream>
#include <stdio.h>
#include <queue>
#include <string.h>
using namespace std;
int a[5][5], vist[5][5]; //vist记录数组同时也记录路径
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
int len = 0;
//typedef pair<int, int> P;
struct Node{
int x, y;
};
typedef struct Node node;
node path[50], p;
void bfs(int sx, int sy, int gx, int gy){
memset(vist, 0, sizeof(vist));
queue<node> que;
p.x = 0, p.x = 0;
que.push(p);
while(!que.empty()){
p = que.front(); que.pop();
if(p.x == gx && p.y == gy) {
len = vist[gx][gy]; // len表示路程长度
break;
}
for(int i = 0; i < 4; i++){
int nx = p.x + dx[i], ny = p.y + dy[i];
if(0 <= nx && nx <= 4 && 0 <= ny && ny <= 4 && a[nx][ny] == 0 && !vist[nx][ny]){
vist[nx][ny] = vist[p.x][p.y] + 1; // +1记录路径,之后可以回溯
p.x = nx, p.y = ny;
que.push(p);
}
}
}
p.x = 4, p.y = 4;
for(int i = len; i >= 0; i--){ // 从终点开始回溯路径
path[i].x = p.x;
path[i].y = p.y;
for(int j = 0; j < 4; j++){
int xx = path[i].x + dx[j];
int yy = path[i].y + dy[j];
if(0 <= xx && xx <= 4 && 0 <= yy && yy <= 4 && a[xx][yy] == 0 && vist[xx][yy] == vist[p.x][p.y]-1){ // 在路径上的vist前一个点会比后一个点少1
p.x = xx;
p.y = yy;
break;
}
}
if(i == 0) path[0].x = 0, path[0].y = 0;
}
}
int main()
{
for(int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++){
scanf("%d", &a[i][j]);
}
getchar();
}
bfs(0, 0, 4, 4);
for(int i = 0; i <= len; i++)
printf("(%d, %d)\n", path[i].x, path[i].y);
return 0;
}